package com.example.mywanandroid.config;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.multidex.MultiDexApplication;

import com.bumptech.glide.Glide;
import com.example.mywanandroid.BuildConfig;
import com.example.mywanandroid.R;
import com.example.mywanandroid.http.data.HttpBaseResponse;
import com.example.mywanandroid.http.data.HttpResponseInterface;
import com.example.mywanandroid.http.httptool.HttpException;
import com.example.mywanandroid.http.request.HttpFactory;
import com.example.mywanandroid.http.request.ServerAddress;
import com.example.mywanandroid.manager.MyActivityManager;
import com.example.mywanandroid.util.Tools;
import com.google.gson.Gson;
import com.guoxiaoxing.phoenix.picker.Phoenix;
import com.orhanobut.hawk.Hawk;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshInitializer;
import com.tencent.bugly.crashreport.CrashReport;

public class App extends MultiDexApplication {
    private static Context context;
    public static boolean firstOpen;

    @Override
    public void onCreate() {
        super.onCreate();
        firstOpen = true;
        context = this;
        initActivityManager();
        init();
        initCrash();
    }

    //初始化腾讯bugly
    private void initCrash() {
        // 获取当前包名
        String packageName = getPackageName();
        // 获取当前进程名
        String processName = Tools.getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(this, "b42bc1ab9f", BuildConfig.DEBUG, strategy);
//        CrashReport.testJavaCrash();
    }

    public static Context getContext() {
        return context;
    }

    private void initActivityManager() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {

            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                MyActivityManager.getInstance().setCurrentActivity(activity);
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
        });
    }

    /**
     * 一些第三方库和本地代码的初始化设置
     */
    private void init() {
        Hawk.init(context).build();
        setHttpConfig();

        Phoenix.config()
                .imageLoader((mContext, imageView, imagePath, type) -> Glide.with(mContext)
                        .load(imagePath)
                        .into(imageView));
    }

    /**
     * 请求配置
     */
    private void setHttpConfig() {
        HttpFactory.HTTP_HOST_URL = ServerAddress.getApiDefaultHost();
        HttpFactory.httpResponseInterface = new HttpResponseInterface() {
            @Override
            public String getResponseData(Gson gson, String response) {
                if (firstOpen) {
                    firstOpen = false;
                    return response;
                }

                HttpBaseResponse httpResponse = gson.fromJson(response, HttpBaseResponse.class);
                if (httpResponse.errorCode != 0) {
                    throw new HttpException(httpResponse.errorCode, httpResponse.errorMsg);
                }
                return gson.toJson(httpResponse.data);
            }
        };
    }

    /**
     * 设置上拉加载和下拉刷新的样式
     */
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                //全局设置主题颜色
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
                return new ClassicsHeader(context);
            }
        });

        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

        SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
            @Override
            public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
                layout.setEnableFooterFollowWhenLoadFinished(true);
                layout.setEnableAutoLoadMore(false);
            }
        });
    }
}
